#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from subprocess import check_call

import logging
_logger = logging.getLogger(__name__)

# Recreate and run git-aggregator
SOURCES = os.environ.get('SOURCES')
RESOURCES = os.environ.get('RESOURCES')
REPOS_YAML = os.environ.get('REPOS_YAML')

if REPOS_YAML and SOURCES:
    content = REPOS_YAML
    repos_file = os.path.join(RESOURCES, "custom-repos.yml")
    with open(repos_file, 'w+') as file:
        file.write(content)

    _logger.info('Running git aggregator on custom-repos.yml..')
    try:
        check_call([
            'autoaggregate',
            '--config',
            repos_file,
            '--install',
            '--output',
            os.path.join(SOURCES, 'repositories'),
        ])
    except Exception as e:
        _logger.error("IMPORTANT! Couldn't run gitaggregate correctly. This is what we get: %s" % e)
